'''
Need one view for this module:

Check in a user
	search for user by barcode or name
	check in user without reloading page

'''

from django.http import HttpResponse
from django.utils import simplejson
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.contrib.auth.models import User
from userprofile.models import userprofile
from checkin.models import Event
from waivers.models import UserWaiver
from django.template import RequestContext
from userattributes.models import Attribute
from userattributes.models import UserAttribute
from datetime import datetime
from datetime import timedelta

EVENT_CHOICES = (
    ('I', 'Checkin'),
    ('O', 'Checkout'),
)

class CheckinForm(forms.Form):
	eventType = forms.CharField(label=(u'Event'), required=True, max_length=1, widget=forms.Select(choices=EVENT_CHOICES))
	idCard = forms.CharField(label=(u'User ID'), required=False, max_length=30)
	
	def performSearch(self):
		data = self.cleaned_data
		
		if(not data['idCard']):
			return 'Please enter an ID.'
		
		#Does the id_card match one or more users?
		try:
			thisUserProfile = userprofile.objects.get(id_card = data['idCard'])
			thisUser = thisUserProfile.user
		except userprofile.DoesNotExist:
			return 'No user with ID ' + data['idCard'] + ' exists.'
		
		#Has this user checked in in the past hour?
		checkins = Event.objects.filter(user = thisUser, timestamp__gte=(datetime.now() - timedelta(hours=1)))
		#if(len(checkins) > 0 and data['eventType'] == 'I'):
		#	return 'This user has already checked in recently.'
		
		return ''
	
	def save(self):
		data = self.cleaned_data
		
		user = userprofile.objects.get(id_card = data['idCard']).user
		
		event = Event(user=user)
		event.eventType = data['eventType']
		event.save()
		
		return event


class LookupForm(forms.Form):
	userPk = forms.CharField(label=(u'User PK'), required=False, max_length=30, widget=forms.HiddenInput)
	eventType = forms.CharField(label=(u'Event'), required=True, max_length=1, widget=forms.Select(choices=EVENT_CHOICES))
	
	def performSearch(self):
		data = self.cleaned_data
		
		if(not data['userPk']):
			return 'Please select a user. Start typing a name and select the user from the drop-down list.'
		
		#Does the userPk match one or more users?
		try:
			thisUser = User.objects.get(pk = data['userPk'])
		except userprofile.DoesNotExist:
			return 'No user with PK ' + data['userPk'] + ' exists.'
		
		#Has this user checked in in the past hour?
		checkins = Event.objects.filter(user = thisUser, timestamp__gte=(datetime.now() - timedelta(hours=1)))
		#if(len(checkins) > 0 and data['eventType'] == 'I'):
		#	return 'This user has already checked in recently.'
		
		return ''
	
	def save(self):
		data = self.cleaned_data
		
		user = User.objects.get(pk = data['userPk'])
		
		event = Event(user=user)
		event.eventType = data['eventType']
		event.save()
		
		return event


def name_lookup(request):
	results = []
	if request.method == "GET":
		if request.GET.has_key(u'query'):
			value = request.GET[u'query']
			if len(value) > 2:
				last_results = User.objects.filter(last_name__icontains=value)
				first_results = User.objects.filter(first_name__icontains=value)
				model_results = last_results | first_results
				results = [ {"first_name":x.first_name, "last_name":x.last_name, "username":x.username, "user_pk":x.pk } for x in model_results ]
	json = simplejson.dumps(results)
	return HttpResponse(json, mimetype='application/json')


#Find the most recent check-ins and print them as a table
def getRecentCheckins():
	events = Event.objects.order_by('-timestamp')[:10]
	recents = []
	for event in events:
		name = event.user.first_name + " " + event.user.last_name
		userWaivers = UserWaiver.objects.filter(user = event.user)
		if len(userWaivers) > 0:
			waiver = 'Yes'
		else:
			waiver = 'No'
		profile = '/userprofile/view/' + str(event.user.pk)
		username = event.user.username
		pk = event.user.pk
		time = event.timestamp
		for choice in EVENT_CHOICES:
			if choice[0] == event.eventType:
				eventType = choice[1]
		
		#Get highest attribute for user
		userAttributes = UserAttribute.objects.filter(user = event.user)
		sortedAttributes = sorted(userAttributes, key=lambda userAttr: userAttr.attribute.priority, reverse=True)
		attribute = "none"
		if len(sortedAttributes) > 0:
			attribute = sortedAttributes[0].attribute.name
		
		thisEvent = {'name':name, 'waiver':waiver, 'profile':profile, 'username':username, 'pk':pk, 'attribute':attribute, 'time':time, 'type':eventType}
		recents.append(thisEvent)
	return recents


#Front-end user check-in (card swipe)
def checkin(request):
	message = ''
	success = False
	
	if request.method == 'POST':
		form = CheckinForm(request.POST)
		if form.is_valid():
			message = form.performSearch()
			if len(message) == 0:
				newEvent = form.save()
				success = True
				
				message = "User is now "
				if newEvent.eventType == 'I':
					message += "checked in."
				else:
					message += "checked out."
	else:
		form = CheckinForm()
	
	recents = getRecentCheckins();
	
	return render_to_response("checkin/checkin.html", {'form':form, 'message':message, 'recents':recents, 'success':success, 'csrf_token':csrf(request)['csrf_token']}, context_instance=RequestContext(request))


#Back-end staff check-in (name lookup)
def lookup(request):
	message = ''
	success = False
	
	if request.method == 'POST':
		form = LookupForm(request.POST)
		if form.is_valid():
			message = form.performSearch()
			if len(message) == 0:
				newEvent = form.save()
				success = True
				
				message = "User is now "
				if newEvent.eventType == 'I':
					message += "checked in."
				else:
					message += "checked out."
	else:
		form = LookupForm()
	
	recents = getRecentCheckins();
	
	return render_to_response("checkin/lookup.html", {'form':form, 'message':message, 'recents':recents, 'success':success, 'csrf_token':csrf(request)['csrf_token']}, context_instance=RequestContext(request))